﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CoreAudioApi;
using Microsoft.Win32;
using DukeySoundHelper.API;

using System.IO;
using DukeySoundHelper.Properties;
using System.Threading;
using System.Runtime.InteropServices;
using System.Resources;
namespace DukeySoundHelper
{
    public partial class MainForm : Form
    {
        private MMDevice device;
        private Thread threadad = null;
        private Thread readResThread = null;//读取资源文件
        private Thread IsRegThread = null;
        int adindex = 0;
        ShowVolumnFrm frm = new ShowVolumnFrm();
        public MainForm()
        {
            DukeyComm.lang = Settings.Default.lang;
            if (DukeyComm.lang == "english")
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
            InitializeComponent();
            //OperatingSystem os = Environment.OSVersion;
            //MessageBox.Show(os.Version.ToString());
            //MessageBox.Show(os.Platform.ToString());
        }
 
        void AudioEndpointVolume_OnVolumeNotification(AudioVolumeNotificationData data)
        {
            if (this.InvokeRequired)
            {
                object[] Params = new object[1];
                Params[0] = data;
                this.Invoke(new AudioEndpointVolumeNotificationDelegate(AudioEndpointVolume_OnVolumeNotification), Params);
            }
            else
            {
                tbMaster.Value = (int)(Math.Round(data.MasterVolume, 2) * 100);               
                label1.Text = " " + tbMaster.Value;
            }
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            InitConfig();
            MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
            device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
            tbMaster.Value = (int)(device.AudioEndpointVolume.MasterVolumeLevelScalar * 100);
            label1.Text = "  " + tbMaster.Value;
            device.AudioEndpointVolume.OnVolumeNotification += new AudioEndpointVolumeNotificationDelegate(AudioEndpointVolume_OnVolumeNotification);

            //this.Visible = false;
            HotKey.RegisterHotKey(Handle, 100, GetKeyZuhe(cboxup1.Text), Keys.Up); //定义热键为Alt+Tab，这里实现了屏幕系统Alt+Tab键             
            HotKey.RegisterHotKey(Handle, 200, GetKeyZuhe(cbdown1.Text), Keys.Down); //注册2个热键,根据id值100,200来判断需要执行哪个函数
            HotKey.RegisterHotKey(Handle, 300, HotKey.KeyModifiers.Ctrl, Keys.F12); //注册2个热键,根据id值100,200来判断需要执行哪个函数
           
            RunWhenStart(DukeyComm.AutoStart, Application.ProductName, Application.ExecutablePath);
         
                this.Visible = false;
            
            timer1.Enabled = true;
            RegisterAppBar(false);
            threadad = new Thread(new ThreadStart(ReadAdConfig));
            threadad.Start();

            readResThread = new Thread(new ThreadStart(ReadRes));
            readResThread.Start();
        }
        private void ReadRes()
        {
            Thread.Sleep(2000);
            //读取资源文件判断是否注册

            DukeyComm.pubKey = Properties.Resources.pubkey;
            //Comm.signKey = rm.GetString("SignKey");  
            
            try
            {
                System.IO.StreamReader sr = new System.IO.StreamReader("auth.dat");
                DukeyComm.signKey = sr.ReadToEnd();
                sr.Close();
            }
            catch { }
            readResThread.Abort();

        }
        
        private void tbMaster_Scroll(object sender, EventArgs e)
        {
            //device.AudioEndpointVolume.MasterVolumeLevelScalar = ((float)tbMaster.Value / 100.0f);
            device.AudioEndpointVolume.MasterVolumeLevelScalar = (float)Math.Round(((decimal)tbMaster.Value / 100), 2);
            
           //bool isfullscreen = new FullScreen().IsFullWindow();
            if (this.Visible==false && isfullScreen==false)
            {
                frm.timer1.Interval = DukeyComm.waitseconds * 1000;
                frm.timer1.Enabled = false;
                frm.panel1.Width =tbMaster.Value*6;
                frm.label1.Text = " " + tbMaster.Value + "%";
                frm.label2.Text = DateTime.Now.ToString("HH:mm");
                
                frm.panel1.BackColor = DukeyComm.ToColor(DukeyComm.backcolor);
                if (!(DukeyComm.WinPopLeft == -1 && DukeyComm.WinPopTop == -1))
                {
                    frm.Location = new Point(DukeyComm.WinPopLeft, DukeyComm.WinPopTop);
                }
                else
                {
                    frm.StartPosition = FormStartPosition.CenterScreen;
                }
                frm.Show();
                frm.timer1.Enabled = true;
            }
                 
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            //this.WindowState = FormWindowState.Minimized;
            this.Visible = false;

        }

        protected override void WndProc(ref Message m)//监视Windows消息       
        {
            const int WM_HOTKEY = 0x0312;//如果m.Msg的值为0x0312那么表示用户按下了热键       
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    ProcessHotkey(m);//按下热键时调用ProcessHotkey()函数              
                    break;                  
            }
            if (m.Msg == uCallBackMsg)
            {
                switch (m.WParam.ToInt32())
                {
                    case (int)ABNotify.ABN_FULLSCREENAPP:
                        {
                            if ((int)m.LParam == 1)
                                this.isfullScreen = true;
                            else
                                this.isfullScreen = false;
                            break;
                        }
                    default:
                        break;
                }
            }
            base.WndProc(ref m); //将系统消息传递自父类的WndProc    
        }      

        private void ProcessHotkey(Message m) //按下设定的键时调用该函数       
        {           
            IntPtr id = m.WParam; //IntPtr用于表示指针或句柄的平台特定类型            //MessageBox.Show(id.ToString());       
            string sid = id.ToString();
            int change = int.Parse(cbChange.Text);
            switch (sid)
            {
                case "100":
                    {
                        //device.AudioEndpointVolume.MasterVolumeLevelScalar = ((float)tbMaster.Value / 100.0f);

                        if ((tbMaster.Value + change) > 100)
                            tbMaster.Value = 100;
                        else
                        {
                            tbMaster.Value += change;
                            if (tbMaster.Value == 29)
                                tbMaster.Value = 30;
                        }
                        //label1.Text = "主音量 " + tbMaster.Value;
                        this.Invoke(new EventHandler(tbMaster_Scroll));
                    }
                    break;

                case "200":
                    {
                        if ((tbMaster.Value - change) < 0)
                            tbMaster.Value = 0;
                        else
                        {
                            tbMaster.Value -= change;                            
                        }
                        //label1.Text = "主音量 " + tbMaster.Value;
                        this.Invoke(new EventHandler(tbMaster_Scroll));
                    }
                    break;

                case "300"://静音
                    device.AudioEndpointVolume.Mute = !device.AudioEndpointVolume.Mute;
                    break;
            }
            GC.Collect();
        }

        private void 显示主窗口ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.notifyIcon1.Visible = false;
            HotKey.UnregisterHotKey(Handle, 100);//卸载第1个快捷键         
            HotKey.UnregisterHotKey(Handle, 200); //缷载第2个快捷键
            HotKey.UnregisterHotKey(Handle, 300); //缷载第2个快捷键
            RegisterAppBar(true);//取消注册全屏钩子
            int unit=0;
            int.TryParse(cbChange.Text,out unit);
            DukeyComm.ChangeUnit = unit;
            Settings.Default.autostart = DukeyComm.AutoStart;
            Settings.Default.ChangeUnit = DukeyComm.ChangeUnit;
            Settings.Default.IsMouseLeft = DukeyComm.IsMouseLeft;
            Settings.Default.IsMouseRight = DukeyComm.IsMouseRight;
            Settings.Default.Highkey = DukeyComm.Highkey;
            Settings.Default.Lowkey = DukeyComm.Lowkey;           
            Settings.Default.Save();
            Environment.Exit(0);
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {

            this.Visible = !this.Visible;
            if (this.Visible == true)
            {
                this.WindowState = FormWindowState.Normal;
                this.TopMost = true;
            }
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Visible = false;
            }
            else
            {
                this.TopMost = true;
            }
        }

        /// <summary> 
        /// 开机启动项 
        /// </summary> 
        /// <param name="Started">是否启动</param> 
        /// <param name="name">启动值的名称</param> 
        /// <param name="path">启动程序的路径</param> 

        public void RunWhenStart(bool Started, string name, string path)
        {
            RegistryKey HKLM = Registry.LocalMachine;
            RegistryKey Run = null;
            try
            {
                Run = HKLM.CreateSubKey(@"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\");
            }
            catch { }
            if (Started == true)
            {
                try
                {
                    if (Run.GetValue(name) == null)
                    {
                        Run.SetValue(name, path); 
                        //保存设置          
                        DukeyComm.AutoStart = true;
                        Settings.Default.autostart = DukeyComm.AutoStart;
                        Settings.Default.Save();
                        autoStartItem.Text = DukeyComm.AutoStart ? "√AutoStart(Status:Open)" : "AutoStart(Status:Close)";
                    }
                    HKLM.Close();
                  
                }
                catch (Exception)
                {
                    //MessageBox.Show("设置开机启动失败,可能是因为360安全卫士或qq电脑管家阻止了该操作!","都客音量调节助手");
                    DukeyComm.AutoStart = false;
                    Settings.Default.autostart = DukeyComm.AutoStart;
                    Settings.Default.Save();
                    autoStartItem.Text = DukeyComm.AutoStart ? "√AutoStart(Status:Open)" : "AutoStart(Status:Close)";
                         MessageBox.Show("failed to boot start","Error");
                }
            }
            else
            {
                try
                {
                    if (Run.GetValue(name) != null)
                    {
                        Run.DeleteValue(name);
                        //保存设置          
                        DukeyComm.AutoStart = false;
                        Settings.Default.autostart = DukeyComm.AutoStart;
                        Settings.Default.Save();
                        autoStartItem.Text = DukeyComm.AutoStart ? "√AutoStart(Status:Open)" : "AutoStart(Status:Close)";
                        HKLM.Close();
                    }
                    else
                        return;
                }
                catch (Exception e)
                {
                    DukeyComm.AutoStart = false;
                    Settings.Default.autostart = DukeyComm.AutoStart;
                    Settings.Default.Save();
                    autoStartItem.Text = DukeyComm.AutoStart ? "√AutoStart(Status:Open)" : "AutoStart(Status:Close)";
                    //MessageBox.Show(e.Message.ToString()+"注册表拒绝访问!");
                }
            }
        }

        private void autoStartItem_Click(object sender, EventArgs e)
        {
            DukeyComm.AutoStart = !DukeyComm.AutoStart;          
            RunWhenStart(DukeyComm.AutoStart, Application.ProductName, Application.ExecutablePath);           
        }

        #region 加载配置文件

        private void InitConfig()
        {
            //读取资源文件



            DukeyComm.AutoStart = Settings.Default.autostart;
            autoStartItem.Text = DukeyComm.AutoStart ? "√AutoStart(Status:Open)" : "AutoStart(Status:Close)";

            DukeyComm.IsMouseLeft = Settings.Default.IsMouseLeft;
            checkBox1.Checked = DukeyComm.IsMouseLeft;

            DukeyComm.IsMouseRight = Settings.Default.IsMouseRight;
            checkBox2.Checked = DukeyComm.IsMouseRight;

            DukeyComm.Highkey = Settings.Default.Highkey;
            cboxup1.Text = DukeyComm.Highkey;
            DukeyComm.Lowkey = Settings.Default.Lowkey;
            cbdown1.Text = DukeyComm.Lowkey;
            DukeyComm.ChangeUnit = Settings.Default.ChangeUnit;
            cbChange.Text = DukeyComm.ChangeUnit.ToString();

             DukeyComm.backcolor=Settings.Default.backcolor;
             DukeyComm.waitseconds=Settings.Default.waitseconds;
             DukeyComm.WinPopLeft=Settings.Default.WinPopLeft ;
             DukeyComm.WinPopTop = Settings.Default.WinPopTop;
             


        }
        #endregion

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string url = "";
            LinkLabel link = (LinkLabel)sender;
            if (link.Tag == null)
            {
                url = "http://hi.baidu.com/38809972/blog/item/5a08e05835f4af92800a188e.html?" + DateTime.Now.ToString("yyMMddHHss");
            }
            else
            {
                url = link.Tag.ToString();
            }
            System.Diagnostics.Process.Start("explorer.exe",url);
        }


        /// <summary>
        /// 获取键盘转换
        /// </summary>
        /// <param name="keyvalue"></param>
        /// <returns></returns>
        private HotKey.KeyModifiers GetKeyZuhe(string keyvalue)
        {
            //Ctrl,Alt,Shift,Win
            HotKey.KeyModifiers key = HotKey.KeyModifiers.None;
            switch (keyvalue)
            {
                case "Ctrl": key = HotKey.KeyModifiers.Ctrl; break;
                case "Alt": key = HotKey.KeyModifiers.Alt; break;
                case "Shift": key = HotKey.KeyModifiers.Shift; break;
                case "Win": key = HotKey.KeyModifiers.WindowsKey; break;
            }
            return key;
        }

        private void cboxup1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //HotKey.UnregisterHotKey(Handle, 100);//卸载第1个快捷键 
            DukeyComm.Highkey = cboxup1.Text;
            HotKey.RegisterHotKey(Handle, 100, GetKeyZuhe(cboxup1.Text), Keys.Up); //定义热键为Alt+Tab，这里实现了屏幕系统Alt+Tab键         
            Settings.Default.Highkey = DukeyComm.Highkey;
            Settings.Default.Save();

        }
        private void cbdown1_SelectedIndexChanged(object sender, EventArgs e)
        {
            DukeyComm.Lowkey = cbdown1.Text;
            HotKey.RegisterHotKey(Handle, 200, GetKeyZuhe(cbdown1.Text), Keys.Down); //注册2个热键,根据id值100,200来判断需要执行哪个函数               
            Settings.Default.Lowkey = DukeyComm.Lowkey;
            Settings.Default.Save();
        }
        private void timer1_Tick(object sender, EventArgs e)
        {

            if (DukeyComm.ds != null && DukeyComm.ds.Tables.Count>0)
            {
                if (adindex > DukeyComm.ds.Tables[0].Rows.Count - 1)
                    adindex = 0;
                else
                {
                    linkad.Text = DukeyComm.ds.Tables[0].Rows[adindex]["link_text"].ToString();
                    linkad.Tag = DukeyComm.ds.Tables[0].Rows[adindex]["url"].ToString();
                    adindex++;
                }
            }
            else
            {
                linkad.Tag = "http://hi.baidu.com/38809972/blog/item/5a08e05835f4af92800a188e.html?" + DateTime.Now.ToString("yyMMddHHss");
            }

        }

        private void ReadAdConfig()//读取配置文件
        {
            try
            {
                DukeyComm.ds.ReadXml("http://www.mou18.com/ashx/showad.ashx?soft=soundhelper", XmlReadMode.InferSchema);
            }
            catch
            {
                DukeyComm.ds = null;
            }
            finally
            {
                threadad.Join();
                threadad = null;
            }
            //DataTable xmlTable = DukeyComm.ds.Tables[0];
            //foreach (DataRow rows in xmlTable.Rows)
            //{
            //    MessageBox.Show(rows["url"].ToString());
            //    rows["link_text"].ToString();
            //}
        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //http://hi.baidu.com/38809972/blog/item/5a08e05835f4af92800a188e.html
            System.Diagnostics.Process.Start("explorer.exe", "http://hi.baidu.com/38809972/blog/item/5a08e05835f4af92800a188e.html?" + DateTime.Now.ToString("yyMMddHHss"));
        }


        //以下处理鼠标事件
        #region 按住鼠标左键+滚轮调节音量
        private void checkBox1_CheckedChanged(object sender, EventArgs e)//按住鼠标左键+滚轮调节音量
        {
            if (checkBox1.Checked)
            {
                if (!IsStartMouseDown)
                {
                    //HookManager.MouseDown += HookManager_MouseDown;
                    //HookManager.MouseUp += HookManager_MouseUp;                
                    IsStartMouseDown = true;
                }
            }
            else
            {
                //HookManager.MouseDown -= HookManager_MouseDown;
            }
            DukeyComm.IsMouseLeft = checkBox1.Checked;
        }
        #endregion

        private void HookManager_MouseUp(object sender, MouseEventArgs e)
        {
            //HookManager.MouseWheel -= HookManager_MouseWheel;
            IsStartMouseDown = false;
        }

        bool IsStartMouseDown = false;
        private void HookManager_MouseDown(object sender, MouseEventArgs e)
        {
            //if (e.Button == MouseButtons.Left && checkBox1.Checked)
            //{
            //    HookManager.MouseWheel += HookManager_MouseWheel;
            //}
            //if (e.Button == MouseButtons.Right && checkBox2.Checked)
            //{
            //    HookManager.MouseWheel += HookManager_MouseWheel;
            //}
        }





        private void HookManager_MouseWheel(object sender, MouseEventArgs e)
        {
            int change = int.Parse(cbChange.Text);
            if (e.Delta > 0)
            {
                if ((tbMaster.Value + change) > 100)
                    tbMaster.Value = 100;
                else
                {
                    tbMaster.Value += change;
                    if (tbMaster.Value == 29)
                        tbMaster.Value = 30;
                }
                //label1.Text = "主音量 " + tbMaster.Value;
                this.Invoke(new EventHandler(tbMaster_Scroll));
            }
            else
            {
                if ((tbMaster.Value - change) < 0)
                    tbMaster.Value = 0;
                else
                {
                    tbMaster.Value -= change;
                }
                this.Invoke(new EventHandler(tbMaster_Scroll));
            }
            //labelWheel.Text = string.Format("Wheel={0:000}", e.Delta);
        }

        #region 按住鼠标右键+滚轮调节音量
        private void checkBox2_CheckedChanged(object sender, EventArgs e)//按住鼠标右键+滚轮调节音量
        {
            if (checkBox2.Checked)
            {
                if (!IsStartMouseDown)
                {
                    //HookManager.MouseDown += HookManager_MouseDown;
                    //HookManager.MouseUp += HookManager_MouseUp;
                    IsStartMouseDown = true;
                }
            }
            else
            {
                //HookManager.MouseDown -= HookManager_MouseDown;
            }
            DukeyComm.IsMouseRight = checkBox2.Checked;
        }
        #endregion

        private void 下载新版本ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("this version is lastest!", "check version");
            System.Diagnostics.Process.Start("explorer.exe", "http://hi.baidu.com/38809972/blog/item/5a08e05835f4af92800a188e.html?" + DateTime.Now.ToString("yyMMddHHss"));
            ////启动更新独立程序          
            //string AppName = "DukeyVoice";
            //string processName = "DukeyVoice";
            //string version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            //string updatexml = "http://www.mou18.com/soft/DukeyVolume/update.xml";
            //string args = AppName + "|" + processName + "|" + version + "|" + updatexml;

            //System.Diagnostics.Process pro = new System.Diagnostics.Process();
            //pro.StartInfo.FileName = System.IO.Directory.GetCurrentDirectory() + @"\LsUpdater.exe ";
            //pro.StartInfo.UseShellExecute = false;
            //pro.StartInfo.Arguments = args;
            //pro.Start();
            //pro.Close();           
        }


        #region 检查全屏
        int uCallBackMsg = 0;//检查全屏
        private void RegisterAppBar(bool registered)
        {
            APPBARDATA abd = new APPBARDATA();
            abd.cbSize = Marshal.SizeOf(abd);
            abd.hWnd = this.Handle;
            if (!registered)
            {
                //register  
                uCallBackMsg = APIWrapper.RegisterWindowMessage("APPBARMSG_CSDN_HELPER");
                abd.uCallbackMessage = uCallBackMsg;
                uint ret = APIWrapper.SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);
            }
            else
            {
                APIWrapper.SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);
            }
        }
        bool isfullScreen = false;
     
        #endregion
        
        private void 高级设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(SetConfig.instance.Visible==false)
            SetConfig.instance.ShowDialog();
        }

        private void 注册ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (RegisterFrm.instance.Visible == false)
                RegisterFrm.instance.ShowDialog();
            
        }
        string isregstr = "";
        private void IsRegister()
        {
            Thread.Sleep(50000);
            CheckForIllegalCrossThreadCalls = false;
            lock (this)
            {
                if (DukeyComm.signKey != "" && CryptRSA.CheckAuth(WMICardGrab.GetCPUId(), DukeyComm.signKey, DukeyComm.pubKey))
                {
                    //isregstr = "[registered]";
                }
                else
                {
                    RegisterFrm frm = new RegisterFrm();
                    frm.ShowDialog();
                    isregstr = "[unregistered]";
                }
                this.Text += isregstr;
                IsRegThread.Abort();
            }
        }


        private void MainForm_Shown(object sender, EventArgs e)
        {
            //IsRegThread = new Thread(new ThreadStart(IsRegister));
            //IsRegThread.Start();
            //CheckUpdate();
        }
        private void cbChange_SelectedIndexChanged(object sender, EventArgs e)
        {
            DukeyComm.ChangeUnit = int.Parse(cbChange.Text);
            Settings.Default.ChangeUnit = DukeyComm.ChangeUnit;
            Settings.Default.Save();
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {

        }
        //private void CheckUpdate()
        //{
        //    LsUpdater.API.UpdateHelper.Instance.AppName = "DukeyVoice";//程序名称
        //    LsUpdater.API.UpdateHelper.Instance.ProcessName = "DukeyVoice";//文件名称
        //    LsUpdater.API.UpdateHelper.Instance.CurrentVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();//版本号            

        //    LsUpdater.API.UpdateHelper.Instance.UpdateXmlUrl = "http://www.mou18.com/soft/DukeyVolume/update.xml";//update.xml配置文件地址
        //    LsUpdater.API.UpdateHelper.Instance.IsMustUpdate = false;//可选,默认false

        //    //第一种调用方式,使用线程
        //    LsUpdater.API.UpdateHelper.Instance.WaitTime = 5000;//等待5000毫秒启动应用程序
        //    LsUpdater.API.UpdateHelper.Instance.TheadUpdate.Start();

        //    //第二种调用:直接调用
        //    //LsUpdater.API.UpdateHelper.Instance.CheckUpdate();
        //}
    }
}
